from django.contrib.auth import logout
from django.shortcuts import render,redirect,reverse
from django.views import View
from .form import RegisterForm,LoginForm
from .models import User
from utils.return_json import json_response
from  utils.return_code import Code
import logging
# Create your views here.
logger=logging.getLogger("mypro")
logger.setLevel(logging.DEBUG)
consolo=logging.StreamHandler()
consolo.setLevel(logging.INFO)
fmat=logging.Formatter(
    'time:%(asctime)s'+"/"
    'level:%(levelname)s'+"/"
    'message:%(message)s'
)





class Login(View):
    def get(self,request):
        return render(request, "user/login.html")
    def post(self,request):
        form=LoginForm(request.POST,request=request)
        if form.is_valid():
            logger.info("验证成功")
            return json_response(errmsg="恭喜你登录成功")
        else:
            logger.info("验证失败")
            error_list = []
            for item in form.errors.get_json_data().values():
                error_list.append(item[0].get("message"))
            error_msg = '/'.join(error_list)
            return json_response(errno=Code.REGISTER, errmsg=error_msg)


class LoginOut(View):
    def get(self,request):
        logout(request)
        return redirect(reverse("user:login"))


class Register(View):
    def get(self,request):
        return render(request, "user/register.html")
    def post(self,request):
        form=RegisterForm(request.POST,request=request)
        if form.is_valid():
            username=form.cleaned_data.get("username")
            password=form.cleaned_data.get("password")
            mobile=form.cleaned_data.get("mobile")
            User.objects.create_user(username=username,password=password,mobile=mobile)
            logger.info("注册成功")
            return json_response(errmsg="恭喜你注册成功")
        else:
            error_list=[]
            for item in form.errors.get_json_data().values():
                error_list.append(item[0].get("message"))
            error_msg='/'.join(error_list)
            return json_response(errno=Code.REGISTER,errmsg=error_msg)

